package com.gxa.jd.controller.front;

import com.gxa.entity.Result;
import com.gxa.exception.CustomerException;
import com.gxa.jd.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



@Controller
@Slf4j
@RequestMapping("/front/pay")
public class PayController {


    @Autowired
    private PayService payService;



    /**
     * 聚合支付请求发起
     * @param payToken
     * @param response
     * @throws CustomerException
     * @throws IOException
     */
    @RequestMapping("/create")
    public void pay(@RequestParam("payToken")  String payToken,@RequestParam("payType")Integer payType, HttpServletResponse response) throws CustomerException, IOException {
       payService.pay(payToken,payType,response);
    }


    //同步通知
    @RequestMapping("/callback/returnUrl")
    @ResponseBody
    public Result synCallBack(@RequestParam Map<String, String> params) {
        log.info("#####支付宝同步通知synCallBack#####开始,params:{}", params);
        try {
            if (!payService.verifyResult()) {
                return new Result(50000,"支付异常!");
            }
            // 商户订单号
            String outTradeNo = params.get("out_trade_no");
            // 支付宝交易号
            String tradeNo = params.get("trade_no");
            // 付款金额
            String totalAmount = params.get("total_amount");
            Map map=new HashMap();
            map.put("outTradeNo",outTradeNo);
            map.put("tradeNo",tradeNo);
            map.put("totalAmount",totalAmount);
            return new Result(map);
        } catch (Exception e) {
            log.error("####支付宝同步通知出现异常,ERROR:", e);
            return new Result(50000,"支付异常!");
        } finally {
            log.info("#####支付宝同步通知synCallBack#####结束,params:{}", params);
        }

    }


    //异步通知
    @PostMapping("/callback/notify")
    @ResponseBody
    public String payNotify(@RequestParam Map<String, String> params){
        log.info("#####支付宝异步通知synCallBack#####开始,params:{}", params);
        try {
            return payService.asynCallBack(params);
        }catch (CustomerException e) {
            log.error("支付通知失败!原因:{}",e.getMessage());
            return "fail";
         } catch (Exception e){
            log.error("支付通知失败!原因:{}",e.getMessage());
            return "fail";
        }finally {
            log.info("#####支付宝异步通知synCallBack#####结束,params:{}", params);
        }
    }


}
